package com.portal.portal.config;

import java.io.IOException;
import java.io.InputStream;

import org.xml.sax.SAXException;

import com.sun.org.apache.commons.digester.Digester;

public class ResourceConfigReader {

  public static final String DRIVER_CONFIG_FILE = "/WEB-INF/jojo-portal-driver-config.xml";
  private static ResourceConfigReader factory;
  private Digester digester;

  public static ResourceConfigReader getFactory() {
    if (factory == null) {
      factory = new ResourceConfigReader();
    }
    return factory;
  }

  private ResourceConfigReader() {
    digester = new Digester();
    digester.setClassLoader(Thread.currentThread().getContextClassLoader());
    init();
  }

  public DriverResourceConfig parse(InputStream in) throws IOException, SAXException {
    return (DriverResourceConfig) digester.parse(in);
  }

  // Digester Setup
  private void init() {
    digester.addObjectCreate("jojo-portal-driver", DriverResourceConfig.class);
    digester.addBeanPropertySetter("jojo-portal-driver/portal-name", "portalName");
    digester.addBeanPropertySetter("jojo-portal-driver/portal-version", "portalVersion");
    digester.addBeanPropertySetter("jojo-portal-driver/portlet-container-name", "containerName");

    digester.addCallMethod("jojo-portal-driver/supports/portlet-mode", "addSupportedPortletMode", 0);
    digester.addCallMethod("jojo-portal-driver/supports/window-state", "addSupportedWindowState", 0);

    digester.addObjectCreate("jojo-portal-driver/render-config", DriverRenderConfig.class);
    digester.addSetProperties("jojo-portal-driver/render-config", "default", "defaultPageId");
    digester.addObjectCreate("jojo-portal-driver/render-config/page", DriverPageConfig.class);
    digester.addSetProperties("jojo-portal-driver/render-config/page");
    digester.addCallMethod("jojo-portal-driver/render-config/page/portlet", "addPortlet", 2);
    digester.addCallParam("jojo-portal-driver/render-config/page/portlet", 0, "context");
    digester.addCallParam("jojo-portal-driver/render-config/page/portlet", 1, "name");
    digester.addSetNext("jojo-portal-driver/render-config/page", "addPage");
    digester.addSetNext("jojo-portal-driver/render-config", "setDriverRenderConfig");
  }

}
